package cn.jdemo.socket.zeroCopy;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * <a href="https://zhuanlan.zhihu.com/p/27698585">java-零拷贝</>
 *
 * 使用MappedByteBuffer实现内存共享
 */
public class Mmap02 {
    public static void main(String args[]) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            RandomAccessFile f = null;
            try {
                f = new RandomAccessFile("D:/zerocopy/hello.txt", "rw");
                FileChannel fc = f.getChannel();
                MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 20);

                buf.put("how are you?".getBytes());

                Thread.sleep(10000);

                fc.close();
                f.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        thread1.start();

        Thread.sleep(2*1000);

        Thread thread2 = new Thread(() -> {
            MappedByteBuffer buf = null;
            try {
                RandomAccessFile f = new RandomAccessFile("D:/zerocopy/hello.txt", "rw");
                FileChannel fc = f.getChannel();
                buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size());
            } catch (Exception e) {
                e.printStackTrace();
            }

            while (buf.hasRemaining()) {
                System.out.print((char)buf.get());
            }
            System.out.println();
        });
        thread2.start();
    }
}
